package com.youlu.campus.admin.course.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.youlu.campus.admin.course.dto.ThirdCourseStatisticsDTO;
import com.youlu.campus.admin.course.dto.ThirdCourseVideoSearchDTO;
import com.youlu.campus.admin.course.vo.ThirdCourseOrderStatisticsVo;
import com.youlu.campus.admin.course.vo.ThirdCourseOrderVo;
import com.youlu.campus.admin.course.vo.ThridCourseResultVo;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.FileExportTask;
import com.youlu.campus.service.file.FileExportTaskService;
import com.youlu.campus.service.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.Objects;

/**
 * @author : [dengbo]
 * @className : ThirdOrderService
 * @description : [三方视频]
 * @createTime : [2022/7/12 15:01]
 */
@Service
@Slf4j
public class ThirdOrderService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private FileExportTaskService fileExportTaskService;

    @Autowired
    private FileService fileService;

    @Autowired
    private MongoTemplate mongoTemplate;

    public Page<ThirdCourseOrderVo> getOrderPageInfo(ThirdCourseVideoSearchDTO dto) {
        String url = "http://ycxy.zgycxy.com/index.php/Ycsy/Manage/index";
        ResponseEntity<ThridCourseResultVo> re = restTemplate.postForEntity(url, dto, ThridCourseResultVo.class);
        ThridCourseResultVo resultVo = re.getBody();
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getPageSize());
        return PageableExecutionUtils.getPage(resultVo.getList(), pageRequest, () -> resultVo.getCount());
    }

    public ThirdCourseOrderStatisticsVo getOrderStatistics(ThirdCourseStatisticsDTO dto) {
        String url = "https://ycxy.zgycxy.com/index.php/Ycsy/Manage/course";
        ResponseEntity<ThirdCourseOrderStatisticsVo> re = restTemplate.postForEntity(url, dto, ThirdCourseOrderStatisticsVo.class);
        ThirdCourseOrderStatisticsVo resultVo = re.getBody();
        return resultVo;
    }

    public void exportThirdOrder(ThirdCourseVideoSearchDTO dto, HttpServletResponse response, String optName, String userId) {
        String url = "http://ycxy.zgycxy.com/index.php/Ycsy/Manage/index";
        dto.setPage(1);
        dto.setPageSize(1);
        ResponseEntity<ThridCourseResultVo> re = restTemplate.postForEntity(url, dto, ThridCourseResultVo.class);
        ThridCourseResultVo resultVo = re.getBody();
        long count = resultVo.getCount();
        int num = (int) count;
        ThirdCourseVideoSearchDTO newDTO = new ThirdCourseVideoSearchDTO();
        newDTO.setPage(1);
        newDTO.setPhone(dto.getPhone());
        newDTO.setLogisticsStatus(dto.getLogisticsStatus());
        newDTO.setCategory(dto.getCategory());
        newDTO.setPageSize(num);
        ResponseEntity<ThridCourseResultVo> pageInfo = restTemplate.postForEntity(url, newDTO, ThridCourseResultVo.class);
        String fileName = "三方视频订单导出" + "-" + System.currentTimeMillis() + ExcelTypeEnum.XLSX.getValue();
        FileExportTask fileExportTask = new FileExportTask();
        fileExportTask.setToken(optName);
        fileExportTask.setBizType("order");
        fileExportTask.setStatus(0);
        fileExportTask.setOptUser(optName);
        fileExportTask.setOptUserId(userId);
        fileExportTask.setFileName(fileName);
        fileExportTask.setNum((int) count);
        fileExportTask.setDesc("三方视频订单导出");
        String fileTaskId = fileExportTaskService.create(fileExportTask);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//字节流
        EasyExcel.write(outputStream, ThirdCourseOrderVo.class).sheet(1).doWrite(pageInfo.getBody().getList());
        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        String uploadFileUrl = fileService.uploadFile(inputStream, fileName);
        Query query = new Query().addCriteria(Criteria.where("id").is(fileTaskId));
        Update update = new Update();
        update.set("status", 1);
        update.set("url", uploadFileUrl);
        update.set("updatedTime", new Date());
        mongoTemplate.updateFirst(query, update, FileExportTask.class);

//        String name = "三方视频订单.xlsx";
//        String fileName = new String(name.getBytes(StandardCharsets.UTF_8));
//        try {
//            response.setHeader("content-disposition", "attachment;filename=" + fileName);
//            //设置类型，扩展名为.xlsx
//            response.setContentType("application/vnd.ms-excel");
//            EasyExcel.write(response.getOutputStream(), ThirdCourseOrderVo.class)
//                    .sheet(1).doWrite(pageInfo.getBody().getList());
//        } catch (Exception e) {
//            log.error("exportThirdOrder error", e);
//        } finally {
//            try {
//                response.flushBuffer();
//            } catch (IOException e) {
//                log.error("exportThirdOrder close error", e);
//            }
//        }
    }
}
